import { HttpError, WEBSOCKETS, toSuccess, useEntityManager } from "@sker/core";
import { useData } from "@sker/runtime";
import { AutoDevice } from "@sker/entities";
import { InjectionToken, container } from "tsyringe";
import { z } from "zod";

export default async () => {
    const input = z.object({
        id: z.string(),
        code: z.string(),
        uuid: z.string(),
        timeout: z.number()
    })
    const body = input.parse(useData());
    await useEntityManager(async m => {
        const device = await m.findOne(AutoDevice, { where: { device_uuid: body.uuid } })
        if (!device) throw new HttpError(`无效token`)
        const websockets = container.resolve(WEBSOCKETS)
        const wss = websockets.get(device.device_uuid)
        if (!wss) throw new HttpError(`设备不在线`)
        wss.send(JSON.stringify({
            type: CLOUD_CODE,
            payload: {
                id: body.id,
                code: body?.code,
                timeout: body.timeout
            }
        }), err => {
            if (err) {
                console.error(err)
            }
        })
    })
    return toSuccess(true)
}
interface ICloudCode {
    id: string;
    code: string;
    timeout?: number;
}
const CLOUD_CODE: InjectionToken<ICloudCode> = `CLOUD_CODE`
